/*
 * @Description:配置组件
 * @Author: hyx
 * @Date: 2021-03-19 11:35
 */
// 选择配置
import { defineComponent, PropType } from 'vue'
import { Config, options } from '@/dictionaries/config'
import { isArray } from '@/utils/tools'
const Props = {
	value: [String, Number, Array] as PropType<string | number | any[]>,
	label: [String, Number, Array] as PropType<string | number | any[]>,
	prop: {
		type: String as PropType<string>,
		default: 'status',
		required: true,
	},
	disabled: {
		type: Boolean as PropType<boolean>,
		default: false,
	},
	mode: String as PropType<'multiple' | 'tags'>,
	placeholder: String as PropType<string>,
	allowClear: {
		type: Boolean as PropType<boolean>,
		default: true,
	},
} as const
const FormConfig = defineComponent({
	name: 'form-config',
	props: Props,
	emits: ['change', 'update:value', 'update:label'],
	setup(props, { emit }) {
		function onChange(value: number | Array<string>, option?: Config | Config[]) {
			if (isArray(value)) {
				if (option && isArray(option)) {
					emit(
						'update:label',
						option.map((item: Config) => {
							return item.label
						})
					)
				} else {
					emit('update:label', undefined)
				}
				if (value.length) {
					emit('update:value', value)
					emit('change', value)
				} else {
					emit('update:value', undefined)
				}
			} else {
				if (option && !isArray(option)) {
					emit('update:value', (option as Config).value)
					emit('update:label', (option as Config).label)
					emit('change', (option as Config).value)
				} else {
					emit('update:value', undefined)
					emit('update:label', undefined)
					emit('change', undefined)
				}
			}
		}

		return () => {
			// const def = isTrue(porps.value) ? porps.value + '' : porps.value

			const def = isNaN(Number(props.value)) ? props.value : Number(props.value)

			return (
				<a-select
					onChange={onChange}
					mode={props.mode}
					disabled={props.disabled}
					allowClear={props.allowClear}
					value={def}
					placeholder={props.placeholder}
					options={options[props.prop]}
				/>
			)
		}
	},
})

export default FormConfig
